<?php
class ModelAccountTags extends Model {
    public function setCustomerTags($customer_id,$tags=array()){
        $this->db->query("INSERT INTO " . DB_PREFIX . "customer_tags_history SET customer_id = '" . (int)$this->customer->getId() . "', target_customer_id = '" . (int)$customer_id . "', tags = '" . $this->db->escape(implode(",", $tags)) . "',date_added = NOW() ");
        foreach ($tags as $tag) {
            $tagquery = $this->db->query("SELECT customer_tags_id FROM " . DB_PREFIX . "customer_tags WHERE customer_id = '" . (int)$customer_id . "' and tag = '" . $this->db->escape($tag) . "'");
            if($tagquery->row)
            {
                $this->db->query("UPDATE " . DB_PREFIX . "customer_tags SET tag_count = (tag_count + 1) WHERE customer_tags_id = '" . (int)$tagquery->row['customer_tags_id'] . "'");
            }
            else
            {
                $this->db->query("INSERT INTO " . DB_PREFIX . "customer_tags SET customer_id = '" . (int)$customer_id . "' ,tag = '" . $this->db->escape($tag) . "', tag_count = 1,tag_type=1 ");

            }
        }
    }
    
    public function getCustomerTags($customer_id)
    {
        $query = $this->db->query("SELECT tag,tag_count FROM " . DB_PREFIX . "customer_tags WHERE customer_id = '" . (int)$customer_id . "' order by tag_count desc");
        return $query->rows;
    }
    
    public function getAllTags()
    {
        $query = $this->db->query("SELECT tag,sum(tag_count) tag_count FROM " . DB_PREFIX . "customer_tags group by tag order by tag_count desc");
        return $query->rows;
    }
}